package com.anrongtec.zcpt.authentication;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;

/**
 * 票据操作类
 * @author dut
 *
 */
public class BillOperation {

    /** 认证成功 */
    public static final int FLAG_AUTH_SUCCESS = 0;
    /** 未知错误 */
    public static final int FLAG_UNKNOW_FAILED = -99;
    /** 票据不存在 */
    public static final int FLAG_BILLINFO_LOSTED = -5;
    /** 票据信息为空 */
    public static final int FLAG_BILLINFO_EMPTY = -1;
    /** 权限被拒绝 */
    public static final int FLAG_LIMITS_DENIAL = -2;
    /** 传入信息错误 */
    public static final int FLAG_APPINFO_ERROR = -3;
    /** 票据信息已过期 */
    public static final int FLAG_BILLINFO_LOG_OFF = -4;
	
	/**
	 * 从游标中获取票据信息
	 * @param context 上下文环境
	 * @return 票据信息
	 */
	public static String getBillInfoByCurosr(Context context) throws Exception {
        ContentResolver resolver = context.getContentResolver();
        Uri uri = Uri.parse(JXClientConstans.BillInfo.CONTENT_URI + "/" + context.getPackageName());
        Cursor query = resolver.query(uri, null, null, null, null);
        String billString = null;
        if (query != null) {
            query.moveToFirst();
            if ("0".equals(query.getString(query.getColumnIndex(JXClientConstans.BillInfo.RESULT_CODE)))) {
                billString = query.getString(query
                        .getColumnIndex(JXClientConstans.BillInfo.BILLSTR));
            } else if ("-5".equals(query.getString(query.getColumnIndex(JXClientConstans.BillInfo.RESULT_CODE)))) {
            } else {
                String code = query.getString(query.getColumnIndex(JXClientConstans.BillInfo.RESULT_CODE));
                query.close();
				throw new Exception(getFlagMessage(Integer.parseInt(code)));
			}
            query.close();
        }
		return billString;
	}

    public static String getFlagMessage(int flag) {
        String result = "票据获取出现未知错误";
        switch (flag) {

            case FLAG_LIMITS_DENIAL:
                result = "没有**应用使用权限，请联系管理员进行分配 ";
                break;
            case FLAG_APPINFO_ERROR:
                result = "传入信息错误";
                break;
            case FLAG_BILLINFO_EMPTY:
                result = "票据信息为空，请重新登录";
                break;
            case FLAG_BILLINFO_LOG_OFF:
                result = "票据信息已过期，请重新获取";
                break;
            case FLAG_BILLINFO_LOSTED:
                result = "票据不存在，请重新登录";
                break;
        }
        return result;
    }

	/**
	 * 删除统一认证的票据
	 * @param context 句柄
	 */
	public static void deleteAuthorizeBill(Context context) {
		ContentResolver resolver = context.getContentResolver();
		Uri uri = Uri.parse(JXClientConstans.BillInfo.CONTENT_URI+"/"+context.getPackageName());
		resolver.delete(uri, null, null);
	}
}
